package com.soulkun.smarthome.logic.interceptor

import android.util.Log
import com.soulkun.smarthome.logic.domain.SignatureHeaders
import com.soulkun.smarthome.logic.utils.SignatureUtils
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.io.IOException

class SignatureInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        return chain.proceed(chain.request().setSignature())
    }

    private fun Request.setSignature(): Request {
        var signatureHeaders =
            SignatureHeaders(System.currentTimeMillis().toString(), SignatureUtils.generateNonce())
        val buffer = Buffer()
        val body = try {
            body()?.writeTo(buffer)
            buffer.readUtf8()
        } catch (e: IOException) {
            e.printStackTrace()
            ""
        }
        signatureHeaders = signatureHeaders.copy(
            signature = SignatureUtils.generateSignatureByDefault(
                signatureHeaders,
                url().uri().path,
                url().uri().query,
                body
            )
        )
        return this.newBuilder()
            .addHeader(SignatureHeaders.HEADER_TIMESTAMP, signatureHeaders.timestamp)
            .addHeader(SignatureHeaders.HEADER_NONCE, signatureHeaders.nonce)
            .addHeader(SignatureHeaders.HEADER_SIGNATURE, signatureHeaders.signature)
            .build()
    }

}